//
//  PhotpHallViewController.m
//  OrderSeat
//
//  Created by haiming on 13-10-13.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "PhotoDetailViewController.h"
#import "ShopHomeViewController.h"
#import "ComposePhotoViewController.h"
#import "SimpleCommentsCell.h"
#import "UIImageView+WebCache.h"
#import "ComposeViewController.h"
#import "CommentsViewController.h"
#import "LoginViewController.h"

#define BTN_LIKE_TAG 4001
#define BTN_SHARE_TAG 4003
#define BTN_COMPOST_TAG 4004

#define SHARE_FORMAT @"分享 (%@)"
#define LIKE_FORMAT @"喜欢 (%@)"
#define VIEW_FORMAT @"%@次浏览 %@"
#define COMM_FORMAT @"有%@个点评"

@implementation PhotoDetailViewController

- (id)initWithId:(NSString *)photoId
{
    self = [super initWithNibClass:[PhotoDetailViewController class]];
    if (self) {
        self.photoId = photoId;
        self.photoList = [NSMutableArray arrayWithCapacity:1];
        _dataSource = [[PhotoDetailDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
    
    if (!self.isLoaded || self.isBack) {
        [_dataSource fetchPhotoInfo];
        [self reset];
    }
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"图片详情"];
    
    _commentsTable.dataSource = _dataSource;
    _commentsTable.delegate = _dataSource;
    _theScrollView.hidden = YES;
}

- (void)leftButtonClick:(id)sender
{
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)buttonAction:(id)sender
{
    if ([sender tag] == BTN_LIKE_TAG && _likeBtn.selected) {
        [AppDelegate showMessage:@"亲，每天只能喜欢一次吆"];
        return;
    }
    
    if ([sender tag] == BTN_LIKE_TAG) {
        [_dataSource like];
    }
    if ([sender tag] == BTN_SHARE_TAG) {
        [_dataSource share];
    }
    if ([sender tag] == BTN_COMPOST_TAG) {
        [self compostAction];
    }
}

- (void)compostAction
{
    if(![AppDelegate checkLoginWithDelegate:self]) return;
    
    ComposeViewController *compostVC = [[ComposeViewController alloc] initWithId:_photoId forType:Photo];
    compostVC.parentVC = self;
    [self.navigationController pushViewController:compostVC animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.backController = self;
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (IBAction)orderAction:(id)sender
{
    ShopHomeViewController *shopHomeVC = [[ShopHomeViewController alloc] initWithId:_shopId];
    [AppDelegate changeToShopTabBar:shopHomeVC];
    
    [self.navigationController pushViewController:shopHomeVC animated:YES];
}

- (void)opration:(OprationType)type count:(NSString*)count
{
    if (type == Like) {
        NSString *likeText = [NSString stringWithFormat:LIKE_FORMAT,count];
        [_likeBtn setTitleForNormal:likeText];
        _likeBtn.selected = YES;
        
        [[DbManager sharedManager] insertLike:_photoId type:PhotoLikeType];
    }
}

- (void)setFormValues:(NSDictionary*)dic
{
    self.data = [NSMutableDictionary dictionaryWithDictionary:dic];
    
    NSString *image = [dic objectForKey:@"image"];
    NSString *content = [dic objectForKey:@"content"];
    NSString *fenxiang = [dic objectForKey:@"fenxiang"];
    NSString *xihuan = [dic objectForKey:@"zan"];
    NSString *pname = [dic objectForKey:@"pname"];
    NSString *touxiang = [dic objectForKey:@"touxiang"];
    NSString *viewcount = [dic objectForKey:@"viewcount"];
    NSString *ftime = [dic objectForKey:@"ftime"];
    NSString *dname = [dic objectForKey:@"dname"];
    NSString *xianqu = [dic objectForKey:@"xianqu"];
    NSString *dianpingshu = [dic objectForKey:@"dianpingshu"];
    float pWidth = [[dic objectForKey:@"pwidth"] floatValue];
    float pHeight = [[dic objectForKey:@"pheight"] floatValue];
    pWidth = pWidth <= 0 ? 1 : pWidth;
    pHeight = pHeight <= 0 ? 1 : pHeight;
    
    fenxiang = [NSString stringWithFormat:SHARE_FORMAT,fenxiang];
    xihuan = [NSString stringWithFormat:LIKE_FORMAT,xihuan];
    viewcount = [NSString stringWithFormat:VIEW_FORMAT,viewcount, ftime];
    dianpingshu = [NSString stringWithFormat:COMM_FORMAT, dianpingshu];
    
    _shopId = [dic objectForKey:@"did"];
    _dataSource.commentList = [dic objectForKey:@"pinglun"];
    
    [_logoImage setImageWithURL:[NSURL URLWithString:image]];
    if ([[NSNull null] isEqual:touxiang] || [touxiang isEqualToString:S_EMPTY]) {
        _avatarView.image = [UIImage imageNamed:@"user_avatar.png"];
    }
    else {
        [_avatarView setImageWithURL:[NSURL URLWithString:touxiang]];
    }
    
    _logoImage.width = 290;
    _logoImage.height = pHeight / (pWidth/290);
    [_logoImage addTarget:self action:@selector(ImageTapped:)];
    
    [_shareBtn setTitleForNormal:fenxiang];
    [_likeBtn setTitleForNormal:xihuan];
    _likeBtn.selected = [[DbManager sharedManager] isLike:_photoId type:PhotoLikeType];
    
    _description.text = content;
    _nameLabel.text = pname;
    _browserLabel.text = viewcount;
    _shopNameLabel.text = dname;
    _addressLabel.text = xianqu;
    _commentLabel.text = dianpingshu;
    
    [_commentsTable reloadData];
    [_commentsTable addTarget:self action:@selector(viewCommentsAction:)];
    
    [self reLayoutSubviews];
}

- (void)viewCommentsAction:(id)sender
{
    CommentsViewController *commVC = [[CommentsViewController alloc] initWithId:_photoId andType:PhotoCommType];
    [self.navigationController pushViewController:commVC animated:YES];
}

- (void)reLayoutSubviews
{
    _theScrollView.hidden = NO;
    [_addressLabel autoHeightForMutiLines];
    
    [UIView autoHeightsNoMargin:@[_description, _detailView]];
    [UIView autoLayoutVertical:@[_logoImage, _detailView]];

    [UIView autoHeights:@[_topView, _midView, _commentsTable]];
    [UIView autoLayoutVertical:@[_topView, _midView, _commentsTable]];
    [UIView drawBorders:@[_topView, _midView, _commentsTable]];
    
    [_theScrollView autoHeight];
}

- (void)shareWithData:(NSDictionary *)data
{
    NSString *content = [data objectForKey:@"content"];
    NSString *imageURL = [data objectForKey:@"image"];
    NSString *fxLink = [data objectForKey:@"fxlink"];
    
    [AppDelegate shareWithContent:content andImageURL:imageURL andLink:fxLink];
}

- (void)ImageTapped:(id)sender
{
    NSString *url = [self.data objectForKey:@"image"];
    NSString *content = [self.data objectForKey:@"content"];
    NSString *fenxiang = [self.data objectForKey:@"fenxiang"];
    NSString *zan = [self.data objectForKey:@"zan"];
    NSString *description = [NSString stringWithFormat:@"描述: %@  分享数: %@  赞数: %@",content,fenxiang,zan];
    
    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
    photo.caption = description;
    [_photoList addObject:photo];
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.wantsFullScreenLayout = YES;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    [browser setCurrentPhotoIndex:0];
    
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:nc animated:YES];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return 1;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photoList.count)
        return [_photoList objectAtIndex:index];
    return nil;
}

@end

//=========================================================================
#pragma==============数据源实现==============================================
//=========================================================================

#define CommentsCellId @"SimpleCommentsCell"
#define PHOTO_INFO_TAG 1001
#define PHOTO_LIKE_TAG 1002
#define PHOTO_SHARE_TAG 1003

@implementation PhotoDetailDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if(self) {
        self.viewController = viewController;
        self.commentsCell = [_viewController createCellWithNib:CommentsCellId];
    }
    
    return self;
}

- (void)fetchPhotoInfo
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_PHOTO_INFO, _viewController.photoId];
    [self get:url tag:PHOTO_INFO_TAG];
}

- (void)like
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_PHOTO_LIKE, _viewController.photoId];
    [self get:url tag:PHOTO_LIKE_TAG];
}

- (void)share
{
    NSString *url = [NSString stringWithFormat:API_PHOTO_SHARE, _viewController.photoId];
    [self get:url tag:PHOTO_SHARE_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [SVProgressHUD dismiss];
    CLog(@"%@", request.responseString);
    
    NSDictionary *json = [request.responseData JSONValue];
    NSDictionary *data = [json objectForKey:@"data"];
    
    if (request.tag == PHOTO_INFO_TAG) {
        [_viewController setFormValues:data];
    }
    
    if (request.tag == PHOTO_LIKE_TAG) {
        NSString *likeCount = [[data objectForKey:@"zan"] stringValue];
        [_viewController opration:Like count:likeCount];
    }
    
    if (request.tag == PHOTO_SHARE_TAG) {
        [_viewController shareWithData:data];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    [super requestFailed:request];
}

#pragma mark-=====================================tableview==================
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_commentList objectAtIndex:indexPath.row];
    return [_commentsCell getCellHeight:dic];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _commentList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SimpleCommentsCell *cell = [_viewController createCellWithNib:CommentsCellId tableview:tableView];
    
    NSDictionary *dic = [_commentList objectAtIndex:indexPath.row];
    
    [cell setContent:dic];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

@end




